// 获取全局app对象
const app = getApp()

import Toast from '@vant/weapp/toast/toast'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartsList: null,
    allChecked: false, // 全选
    totalPrice: 0,
    loaded: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onShow(options) {
    Toast.loading({
      duration: 0,
      message: '加载中...'
    });
    // 检查用户登录
    const flag = await app.loginLogic(this)
    if (flag === 1) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
    }
    // 获取购物车列表
    let { result: cartsList } = await wx.cloud.callFunction({
      name: 'goods' + (app.config.env === 'test' ? '-test' : ''),
      data: {
        action: 'get-carts'
      }
    })
    Toast.clear()
    this.setData({
      cartsList,
      loaded: true
    })
  },

  async getUserInfo(e) { // 不要忘了，按钮去获取用户信息登录
    const flag = await app.getUserInfo(e, this)
    if (flag === 1) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
    }
  },

  handleCheckChange ({ detail }) { // 勾选每个商品
    let totalPrice = 0
    for (let [index, item] of this.data.cartsList.entries()) {
      let isChecked = detail.value.includes(index + '')
      if (isChecked) {
        totalPrice += item.goods.price * item.num
      }
      item.checked = isChecked
    }
    this.setData({
      totalPrice,
      cartsList: this.data.cartsList,
      allChecked: detail.value.length === this.data.cartsList.length
    })
  },

  handleCheckAll () { // 全选
    // 是否有1个没有勾选
    let notAllChecked = this.data.cartsList.some(item => !item.checked)
    this.data.cartsList.forEach(item => item.checked = notAllChecked)
    this.setData({
      cartsList: this.data.cartsList,
      totalPrice: notAllChecked ? this.data.cartsList.reduce((pre, cur) => pre + cur.goods.price * cur.num, 0) : 0
    })
  },

  changeNum ({ currentTarget }) { // 改变商品数量
    let { index, action } = currentTarget.dataset
    if (action === '+') { // 增加数量
      this.data.cartsList[index].num ++
    } else { // 减少数量
      if (this.data.cartsList[index].num === 1) {
        // 从购物车删除商品的弹窗
        this.data.cartsList.splice(index, 1)
      } else {
        this.data.cartsList[index].num--
      }
    }
    // this.data.cartsList[index].checked = true
    this.setData({ cartsList: this.data.cartsList })
    this.countPrice()
  },

  countPrice () { // 计算价格
    let checkedCarts = this.data.cartsList.filter(item => item.checked)
    let totalPrice = checkedCarts.reduce((pre, cur) => pre + cur.goods.price * cur.num, 0)
    this.setData({ totalPrice })
  },
  //点击结算
 async handlePay(){
   //判断用户有没有选购商品
   const {totalPrice}=this.data;
   if (totalPrice===0){
      wx.showToast({
        title: '您还没有选购商品',
        icon:"none"
      })
      return;
    }
    let choosedGoods = []
    for (let item of this.data.cartsList) {
      if (item.checked) {
        let tempGoods = {
          _id: item.goodsId,
          allprice: totalPrice,
          num: item.num,
          price: item.goods.price,
          name: item.goods.name,
          src: item.goods.src,
          dec: item.goods.dec,
          dec2: item.goods.dec2
        }
       
        choosedGoods.push(tempGoods)
      }
    }
    app.globalData.orderCache = choosedGoods

    // 创建订单
    wx.cloud.callFunction({
      name: 'orders' + (app.config.env === 'test' ? '-test' : ''),
      data: {
        action: 'add-order',
        goodsList: choosedGoods,
        status: 1 // 1为待支付，2...状态自定义
      }
    })

    //跳转到支付
    wx.navigateTo({
      url: '/pages/car2/pay/pay?totalPrice=' + totalPrice
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})